package com.sbs.demo.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * A context holder class for holding the current userId and authz info
 *
 * @author luwenmin
 */
public class ContextUtil {

    private static Object getRequestAttribute(String headerName) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            return request.getAttribute(headerName);
        }
        return null;
    }

    public static Integer getUserId() {
        Integer userId = (Integer) getRequestAttribute("userId");
        return userId == null ? 0 : userId;
    }

    public static String getMobile() {
        String mobile = (String) getRequestAttribute("mobile");
        return mobile == null ? "" : mobile;
    }

}
